package com.hps.spring.cloud.alibaba.config;

import com.hps.spring.cloud.alibaba.custom.impl.MyRedisTokenStore;
import javax.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

/**
 * @author heps
 * @since 2020/11/4 13:33
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

  @Resource
  private AuthenticationManager authenticationManager;

  @Resource
  private RedisConnectionFactory redisConnectionFactory;

  @Resource
  private UserDetailsService userDetailsService;

  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode("123456");

    // 配置两个客户端，一个用于password认证一个用于client认证
    clients.inMemory().withClient("client_1")
        .resourceIds("order")
        .authorizedGrantTypes("client_credentials", "refresh_token")
        .scopes("select")
        .authorities("oauth2")
        .secret(finalSecret)
        .and().withClient("client_2")
        .resourceIds("order")
        .authorizedGrantTypes("password", "refresh_token", "client_credentials")
        .scopes("server")
        .authorities("oauth2")
        .secret(finalSecret);
  }

  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.tokenStore(new MyRedisTokenStore(redisConnectionFactory))
        .authenticationManager(authenticationManager)
        .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
        .userDetailsService(userDetailsService);
  }

  @Override
  public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    // 允许表单认证
    security.allowFormAuthenticationForClients();
  }
}
